import HttpUtils from '../HttpUtils/HttpUtils';
// 获取当前时间戳
var timestamp = Date.parse(new Date()) / 1000;
Page({
  ...HttpUtils.func,
  data: {
    contentShow: "contentShow",
    shareShow: "shareHide",
    code: "",
    folderCode: 0,
    playTaskId: "",
    name: "",
    currentTimePoints: 0,
    lastTimePoints: 0,
    taskId: 0,
    content: {},
    recommendList: [],
    flag: true,
    studyInfo: [],
    contentList: [],
    courseId: '',
    courseName: '',
    title: '',
  },
  share(event) { //点击分享
    this.setData({
      contentShow: "contentHide",
      shareShow: "shareShow"
    })
  },
  cancel(event) { //取消分享
    this.setData({
      contentShow: "contentShow",
      shareShow: "shareHide",
    })
  },

  // 跳转 详情
  goshowDetail: function(evnet) {
    var courseId = evnet.currentTarget.dataset.courseId;
    var taskId = evnet.currentTarget.dataset.taskId;
    var name = evnet.currentTarget.dataset.name;
    wx.navigateTo({
      url: "../shortVideoDetail/shortVideoDetail?fromPage=task&taskId=" + taskId + '&name=' + name + '&courseId=' + courseId
    });
  },



  articleDetail(event) { //学习
    var courseId = event.currentTarget.dataset.courseid;
    var taskId = event.currentTarget.dataset.taskid;
    var name = event.currentTarget.dataset.name;
    var title = event.currentTarget.dataset.title;
    var pageUrl = "../missionDetail/missionDetail?fromPage=task&taskId=" + taskId + '&name=' + name + '&courseId=' + courseId + '&title=' + title;
    wx.navigateTo({
      url: pageUrl
    })
  },
  goShortVideoDetail(event) {
    wx.navigateTo({
      url: '../shortVideoDetail/shortVideoDetail?assetType=tv'
    })
  },

  onLoad(params) {
    wx.getSystemInfo({
      success: (res) => { //播放器宽度设置
        this.setData({
          screenWidth: res.windowWidth,
          screenHeight: res.screenHeight
        });
        var playTaskId = this.formatDate("yyyyMMdd");
        var random = Math.round(Math.random() * 99999999999) + 100000000000;
        playTaskId += random;
        //从哪个页面跳转的标记
        var fromPage = params.fromPage;
        this.setData({
          "fromPage": fromPage,
          "timeNow": new Date().getTime(),
          "name": params.name,
        });
        if ("News" == fromPage) {
          //非壳类的资产播放视频
          this.setData({
            "code": params.code,
            "folderCode": params.folderCode,
            "playTaskId": playTaskId,
            "name": params.name,
          });
          //获取内容详情3.1.4
          this.loadDetail();
        } else if ("Topic" == fromPage) {
          //从专题详情页点击专题子内容播放
          this.setData({
            "code": params.subCode,
            "folderCode": params.folderCode,
            "topicId": params.code,
            "playTaskId": playTaskId,
            "name": params.name,
            "topicName": params.topicName,
          });
          //获取内容详情3.1.4
          this.loadDetail();

        } else if ("task" == fromPage) {
          //设置标题
          if (params.courseId != '') {
            var title = params.title
            this.setData({
              "courseId": params.courseId,
            })
            // 修改页面标题
            wx.setNavigationBarTitle({
              title: title,
            });
          } else {
            // 修改页面标题
            var title = params.name
            wx.setNavigationBarTitle({
              title: title,
            });
          }
          //从学习任务列表跳转过来的
          this.setData({
            "taskId": params.taskId,
            "playTaskId": playTaskId,
            "title": title,
          });
          //加载任务详情
          this.loadStudyInfo();
        }
      }
    })
  },

  //查询学习任务详情
  loadStudyInfo: function(e) {
    var newUrl = getApp().globalData.dangjianUrl + "/study/studyInfo";
    var params = {};
    params["taskId"] = this.data.taskId + "";
    params = JSON.stringify(params);
    this.httpGet(newUrl, params, "任务详情接口调用失败").then(
      (respData) => {
        var result = respData.data.result.code;
        if (1 == result) {
          var studyInfo = respData.data.study;
          if (null != studyInfo && undefined != studyInfo) {
            var studyinfo = respData.data.study;
            var courseItems = respData.data.study.courseItems;
            courseItems = courseItems.courseItem;
            var contentList = [];
            if (courseItems.length > 1) {
              var flag = true
            } else {
              var flag = false
            }
            var courseName = '';
            for (var index in courseItems) {
              var content = courseItems[index];
              var json = {};
              var thumbnail;
              var imageFile = content.imgItems.imageFile; //获取图片
              if (null != imageFile && "" != imageFile) {
                for (var j in imageFile) {
                  thumbnail = imageFile[0].url;
                  break;
                }
              }
              json["thumbnail"] = thumbnail;
              json["courseId"] = content.courseId;
              json["courseName"] = content.courseName;
              json["courseType"] = content.courseType;
              json["id"] = content.id;
              json["playTime"] = content.playTime;
              json["studyTime"] = content.studyTime;
              json["status"] = content.status;
              //将 秒转成 时间
              var h = Math.floor(content.totalTime / 3600) >= 10 ? Math.floor(content.totalTime / 3600) : '0' + Math.floor(content.totalTime / 3600);
              var m = Math.floor(content.totalTime / 60) >= 10 ? Math.floor(content.totalTime / 60) : '0' + Math.floor(content.totalTime / 60);
              var s = content.totalTime % 60 >= 10 ? content.totalTime % 60 : '0' + content.totalTime % 60;
              json["totalTime"] = '时长  ' + h + ':' + m + ":" + s;
              var courseId = this.data.courseId;
              //第二次进来
              if (courseId != "" && json.courseId != courseId) {
                contentList.push(json);
              }
              if (courseId != "" && json.courseId == courseId) {
                courseName = json.courseName;
              }

              //第一次进来
              if (courseId == "" && courseItems.length > 1 && index != 0) {
                contentList.push(json);
                courseId = courseItems[0].courseId;
                courseName = courseItems[0].courseName;
              }
              //无其他课件
              if (courseId == "" && courseItems.length == 1) {
                contentList.push(json);
                courseId = courseItems[0].courseId;
                courseName = courseItems[0].courseName;
              }
            }
            this.setData({
              studyInfo: studyInfo,
              contentList: contentList,
              code: courseId,
              flag: flag,
              courseName: courseName,
            });
          }
          //加载课件基本信息
          this.loadDetail();
        } else {
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 2000
          })
        }
      }
    );
  },

 
  loadDetail: function(e) {
    //调用内容详情接口,获取内容详情(专题子内容的资产,需要传递subCode值) 
    var params = {};
    var newUrl = getApp().globalData.dangjianUrl + "/content/contentQuery";
    if ("Topic" == this.data.fromPage) {
      params["code"] = this.data.topicId + "";
      params["subCode"] = this.data.code + "";
    } else {
      params["code"] = this.data.code + "";
      params["subCode"] = "";
    }
    params["contentName"] = this.data.name + "";
    params["siteCode"] = getApp().globalData.siteCode + "";
    params = JSON.stringify(params);
    this.httpGet(newUrl, params, "内容详情加载失败").then(
      (respData) => {
        var result = respData.data.result.code;
        if (1 == result) {
          var content = respData.data.content;
          var thumbnail = content.thumbnail;
          if (null == thumbnail || "" == thumbnail) {
            var imageFiles = content.imageFiles;
            for (var j in imageFiles) {
              thumbnail = imageFiles[j].url;
              break;
            }
          }
          this.setData({
            "content.refCode": content.refCode,
            "content.publishTime": content.publishTime,
            "content.name": content.name,
            "content.url": thumbnail,
            "content.duration": content.duration,
            "content.type": content.type,
            "content.description": content.description,
            "content.sourceFrom": null == content.sourceFrom || "" == content.sourceFrom ? "华数" : content.sourceFrom
          });
          //调用播放记录查询接口获取视频播放地址
          this.loadPlayUrl();
          //是否收藏
          this.loadFavor();
          //热门推荐列表
          // this.recommendList();
        } else {
          this.showPageMsg("alert", respData.data.result.description)
        }
      }
    );
  },


  loadPlayUrl: function() {
    //获取图文的正文内容
    var newUrl = getApp().globalData.dangjianUrl + "/content/contentUrlQuery";
    var params = {};
    params["code"] = this.data.code + "";
    params["siteCode"] = getApp().globalData.siteCode + "";
    params["contentType"] = "1";
    params["from"] = "3";
    params = JSON.stringify(params);
    this.httpGet(newUrl, params, "视频地址查询失败").then(
      (respData) => {
        var result = respData.data.result.code;
        if (1 == result) {
          var playUrls = respData.data.content.playUrls;
          this.setData({
            "content.playUrl": playUrls[0].url,
            "content.itemCode": playUrls[0].subCode
          });
        } else {
          this.showPageMsg("alert", respData.data.result.description)
        }
      }
    );
  },

  loadFavor: function() {
    //获取是否已经收藏(如果是专题子内容的收藏,只查询壳的收藏状态)
    var params = {};
    if ("Topic" == this.data.fromPage) {
      params["code"] = this.data.topicId + "";
    } else {
      params["code"] = this.data.code + "";
    }

    params["name"] = this.data.name + "";
    params = JSON.stringify(params);

    var newUrl = getApp().globalData.dangjianUrl + "/member/userContentIsFavor";

    this.httpGet(newUrl, params, "是否收藏接口调用失败").then(
      (respData) => {
        var result = respData.data.result.code;
        if (1 == result) {
          var isFavor = respData.data.favor.isFavor;
          //默认为收藏的状态
          var favorIcon = "../../img/collectFillICON.png";
          if (isFavor == "false") {
            favorIcon = "../../img/collectICON.png";
          }
          this.setData({
            "content.favorIcon": favorIcon,
            "content.isFavor": isFavor
          });
        } else {
          this.showPageMsg("alert", respData.data.result.description)
        }
      }
    );
  },

  favorContent: function(e) {
    //收藏内容
    var status = e.currentTarget.dataset.status;
    var contentName = e.currentTarget.dataset.name;
    status = "false" == status ? 1 : 0;
    var params = {};
    if ("Topic" == this.data.fromPage) {
      params["code"] = this.data.topicId + "";
    } else {
      params["code"] = this.data.code + "";

    }
    params["siteCode"] = getApp().globalData.siteCode + "";
    params["status"] = status + "";
    params["contentName"] = contentName + "";
    params["contentType"] = "1";
    params["columnCode"] = "";
    params = JSON.stringify(params);
    var newUrl = getApp().globalData.dangjianUrl + "/member/userContentFavor";
    this.httpGet(newUrl, params, "内容收藏操作失败").then(
      (respData) => {
        var result = respData.data.result.code;
        var isFavor = "true";
        var favorIcon = "../../img/collectFillICON.png";
        if (1 == result) {
          if (0 == status) {
            favorIcon = "../../img/collectICON.png";
            isFavor = "false";
            this.showPageMsg("tips", "该内容收藏取消成功！");
          } else {
            this.showPageMsg("tips", "该内容收藏成功！");
          }
          this.setData({
            "content.favorIcon": favorIcon,
            "content.isFavor": isFavor
          });
        } else {
          this.showPageMsg("alert", respData.data.result.description)
        }
      }
    );
  },


  //热门推荐
  recommendList: function(e) {
    var folderCode = this.data.folderCode;
    var refCode = this.data.content.refCode;
    if (null != refCode && undefined != refCode && "" != refCode) {
      folderCode = refCode;
    }
    var newUrl = getApp().globalData.dangjianUrl + "/content/contentRecommend";
    var params = {};
    params["code"] = this.data.code + "";
    params["siteCode"] = getApp().globalData.siteCode + "";
    params = JSON.stringify(params);
    this.httpGet(newUrl, params, "热门推荐加载失败").then(
      (respData) => {
        var result = respData.data.result.code;
        if (1 == result) {
          var contents = respData.data.contents.content;
          var contentList = [];
          for (var index in contents) {
            var content = contents[index];
            //将自己本身去掉
            var code = "";
            if ("topic" == this.data.fromPage) {
              code = this.data.topicId;
            } else {
              code = this.data.code;
            }
            if (code != content.code) {
              var json = {};
              var thumbnail = content.thumbnail;
              if (null == thumbnail || "" == thumbnail) {
                var imageFiles = content.imageFiles;
                for (var j in imageFiles) {
                  if (imageFiles[j].type == "240d" || imageFiles[j].type == "QT" || imageFiles[j].type == "180d") {
                    thumbnail = imageFiles[j].url;
                    break;
                  }
                }
              }
              json["name"] = content.name;
              json["publishTime"] = content.publishTime;
              json["url"] = thumbnail;
              json["code"] = content.code;
              json["type"] = content.type;
              json["foldCodes"] = folderCode;
              json["count"] = content.count;
              json["fromNa"] = '' == content.fromNa ? "华数" : content.fromNa;
              json["folderCode"] = folderCode;
              contentList.push(json);
            }
          }
          this.setData({
            "recommendList": contentList
          });
        } else {
          this.showPageMsg("alert", respData.data.result.description)
        }
      }
    );
  },


  bindListnerPlay: function(e) {
    //视频播放记录上传(整数分钟上传)
    var timePoints = e.detail.currentTime;
    //上一次播放时间
    var lastPlayTime = this.data.timeNow;
    //现在时间
    var time = new Date().getTime();
    var different = time - lastPlayTime;
    timePoints = Math.ceil(timePoints);
    this.setData({
      "currentTimePoints": timePoints
    });
    var lastTimePoints = this.data.lastTimePoints;
    if (timePoints > 0 && different > 60 * 1000) {
      //需要上传播放记录,同时将当前的时间点设置到timePoints
      if (timePoints != lastTimePoints) {
        this.setData({
          "lastTimePoints": timePoints,
          "timeNow": time
        });
        //只要上传就传60s,误差忽略
        this.uploadPlayRecord(timePoints);
      }
    }
  },


  onPlayOver: function(e) {
    //视频播放结束上传
    this.uploadPlayRecord(this.data.content.duration);
  },

  onUnload: function(e) {
    //页面被关闭时调用一次
    var currentTimePoints = this.data.currentTimePoints;
    if (currentTimePoints > 0) {
      //此处进度条时间不一定是整数分钟,按照实际的显示,播放时长还是按照60s计算
      this.uploadPlayRecord(currentTimePoints);
    }
  },


  uploadPlayRecord: function(timePoints) {
    var now = this.formatDate("yyyy-MM-dd hh:mm:ss", new Date());
    var params = {};
    if ("Topic" == this.data.fromPage) {
      params["code"] = this.data.topicId + "";
      params["subCode"] = this.data.code + "";
      params["subName"] = this.data.name + "";
      params["taskId"] = this.data.taskId + "";
      params["duration"] = 60;
      params["playTaskId"] = this.data.playTaskId + "";
      params["playtime"] = now + "";
      params["contentType"] = 1;
      params["durationTotal"] = this.data.content.duration + "";
      params["from"] = 1;
      params["type"] = "Topic";
      params["episodeNum"] = "";
      params["timePoints"] = Math.ceil(timePoints / 1000) + "";
      params["name"] = this.data.topicName + "";
      params = JSON.stringify(params);
    } else {
      params["code"] = this.data.code + "";
      // params["subCode"] = this.data.code + "";
      // params["subName"] = this.data.name + "";
      params["taskId"] = this.data.taskId + "";
      params["duration"] = 60;
      params["playTaskId"] = this.data.playTaskId + "";
      params["playtime"] = now + "";
      params["contentType"] = 1;
      params["durationTotal"] = this.data.content.duration + "";
      params["from"] = 1;
      params["type"] = "News";
      params["episodeNum"] = "";
      params["timePoints"] = Math.ceil(timePoints / 1000) + "";
      params["name"] = this.data.content.name + "";
      params = JSON.stringify(params); 
    }
    var newUrl = getApp().globalData.dangjianUrl + "/member/userPlayDuration";

    this.httpGet(newUrl, params, "上传播放记录异常").then(
      (respData) => {
        var result = respData.data.result.code;
        if (1 == result) {
          console.log("上传播放记录成功");
        } else {
          this.showPageMsg("alert", respData.data.result.description)
        }
      }
    );
  },

  // 页面被拉到底部
  onReachBottom: function(e) {
    this.showPageMsg("tips", "没有更多数据了！");
  },
});